﻿using System.ComponentModel;
using System.Data;
using System.Web.UI;
using MyLib.Data;

namespace MyLib.Web.UI {
	/// <summary>
	/// 
	/// </summary>
	public class MyCodeDataSource : DataSourceControl {
		/// <summary>
		/// 
		/// </summary>
		private const string DEFAULT_CODE_FILE_NAME = "SysCode.xml";

		private bool m_prependAllCode = false;

		private bool m_prependEmptyCode = false;

		private string m_codeFileName = "";

		/// <summary>
		/// 
		/// </summary>
		[Browsable(true)]
		[Bindable(false)]
		[Category("Data")]
		[DefaultValue("")]
		public string CodeFileName {
			get {
				return m_codeFileName;
			}

			set {
				System.Diagnostics.Debug.Assert(value != null);

				m_codeFileName = value.Trim();

				if (!m_codeFileName.StartsWith("~/") && !System.IO.Path.IsPathRooted(m_codeFileName)) {
					m_codeFileName = "~/" + m_codeFileName;
				}
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[Browsable(true)]
		[Bindable(false)]
		[Category("Data")]
		[DefaultValue(0)]
		public int CategoryId { get; set; }

		/// <summary>
		/// 
		/// </summary>
		[Browsable(true)]
		[Bindable(false)]
		[Category("Data")]
		[DefaultValue(false)]
		public bool PrependAllCode {
			get {
				return m_prependAllCode;
			}

			set {
				m_prependAllCode = value;

				if (m_prependAllCode)
					m_prependEmptyCode = false;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[Browsable(true)]
		[Bindable(false)]
		[Category("Data")]
		[DefaultValue(false)]
		public bool PrependEmptyCode {
			get {
				return m_prependEmptyCode;
			}

			set {
				m_prependEmptyCode = value;

				if (m_prependEmptyCode)
					m_prependAllCode = false;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="viewName"></param>
		/// <returns></returns>
		protected override DataSourceView GetView(string viewName) {
			if (viewName.Length == 0) {
				viewName = "DefaultView";
			}

			return new MyCodeDataSourceView(this, viewName, CategoryId, PrependAllCode, PrependEmptyCode);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		internal DataTable GetDataTable() {
			var cp = new CodeProvider(Context.Request.MapPath(CodeFileName), new WebCacheProvider(Context));
			return cp.LoadDataTable();
		}

		/// <summary>
		/// 
		/// </summary>
		public MyCodeDataSource() {
			CodeFileName = DEFAULT_CODE_FILE_NAME;
		}
	} // end of MyCodeDataSource.
}
